<?php

// 重置密码
// PUT member.pwd.reset

namespace app\api\resource\member\pwd;
use think\Db;
use think\Loader;
use think\Session;

class Reset
{
    // 方法
    public $_method = ['PUT'];
    // 前置
    public $_pre    = ['sms'];
    // 描述
    public $_description = '重置密码';
    // 参数
    public $_param  = [
        'mobile'   => '手机号',
        'password' => '密码',
        'confpwd'  => '确认密码',
    ];
    // 返回
    public $_return = [
        201 => '重置成功',
        400 => '手机号被篡改',
        422 => '请求参数不合法',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $params['mobile']   = $request->put('mobile/s','','trim');
        $params['password'] = $request->put('password/s','','trim');
        $params['confpwd']  = $request->put('confpwd/s','','trim');

        $validate = Loader::validate('Member');
        if ( !$validate->scene('resetPwd')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $mobile = Session::get('sms.mobile');
        if ($mobile != $params['mobile']) return [400,'手机号被篡改'];

        $data['password'] = md5($params['password']);
        $num = Db::name('member')->where('mobile',$params['mobile'])->update($data);
        if ($num >= 0) {
            // 删除Session中短信码记录
            Session::delete('sms');

            return [ 201,[] ];
        } else {
            return 500;
        }
    }
}